package io.renren.modules.app.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.C;
import io.renren.common.utils.R;
import io.renren.common.utils.SHA1;
import io.renren.common.validator.Assert;
import io.renren.modules.app.dao.UserDao;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.form.LoginForm;
import io.renren.modules.app.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Override
    public UserEntity queryByMobile(String mobile) {
        UserEntity userEntity = new UserEntity();
        userEntity.setMobile(mobile);
        return baseMapper.selectOne(userEntity);
    }

    @Override
    public long login(LoginForm form) {
        UserEntity user = queryByMobile(form.getMobile());
        Assert.isNull(user, "手机号或密码错误");

        //密码错误
        if (!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))) {
            throw new RRException("手机号或密码错误");
        }

        return user.getUserId();
    }

    @Override
    public R getopenid(String code) {
        String screen = C.weixin_screen;
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + C.weixin_appid + "&secret=" + screen + "&code=" + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(url, String.class);

        return R.ok().put("result", result);

    }

    @Override
    public R getUserInfo(String openid, String accessToken) {

        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openid + "&lang=zh_CN";
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(url, String.class);
        String json = null;
        try {
            json = new String(result.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return R.ok().put("result", json);
    }

    @Override
    public R getSignature(String url) {
        String accessToken = getAccessToken();
        Map<String, String> rs = getJsapiTicket(accessToken, url);


        return R.ok().put("result", rs);

    }

    private String getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + C.weixin_appid + "&secret=" + C.weixin_screen;
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(url, String.class);
        JSONObject OpenidJSONO = JSONObject.parseObject(result);
        String accessToken = String.valueOf(OpenidJSONO.get("access_token"));

        return accessToken;
    }


    private Map<String, String> getJsapiTicket(String accessToken, String url) {
        System.out.println("接收到url:" + url);
        try {
            url = URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new RRException("url编码异常");
        }

        System.out.println("编码:" + url);
        Map<String, String> result = new HashMap<>(16);
        // 网页授权接口
        String urlt = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(urlt, String.class);

        JSONObject OpenidJSONO = JSONObject.parseObject(response);
        String errcode = String.valueOf(OpenidJSONO.get("errcode"));
        String errmsg = String.valueOf(OpenidJSONO.get("errmsg"));
        String ticket = String.valueOf(OpenidJSONO.get("ticket"));
        String expires_in = String.valueOf(OpenidJSONO.get("expires_in"));
        result.put("errcode", errcode);
        result.put("errmsg", errmsg);
        result.put("ticket", ticket);
        result.put("expires_in", expires_in);

//随机字符串
        String noncestr = UUID.randomUUID().toString().replace("-", "");
        //时间戳
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
//4获取url
//5、将参数排序并拼接字符串
        String str = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
        System.out.println("加密的str:" + str);
//6、将字符串进行sha1加密
        String signature = SHA1.encode(str);
        Map<String, String> map = new HashMap<>();
        map.put("timestamp", timestamp);
        map.put("accessToken", accessToken);
        map.put("ticket", ticket);
        map.put("noncestr", noncestr);
        map.put("signature", signature);

        return map;

    }

}
